<script lang="ts" setup>
import { h, ref, reactive } from 'vue'
import { useResetReactive } from 'dsrz/hooks/useReset'
import { aesEncrypt, createRef, findTreeByKey, refs, type DsrzH } from 'dsrz/utils'

import api from '@/request'

import CurrencyDemo from '@/components/demo/index.vue'
import {
  ElMessage,
} from 'element-plus'

import type { ColumnItem, Params, FormDetails } from './types'

const {list} = findTreeByKey(api,'specialty')

defineOptions({
  name: 'specialtyPage',
})

const {
  params,
  exposes: { reset },
} = useResetReactive({})

const data = ref([
  {
    deptName: 'deptName',
    name: 'name',
    code: 'code',
    createTime: 'createTime',
    username: 'username',
    phone: 'phone',
    enable: true,
  },
  {
    deptName: 'deptName',
    name: 'name',
    code: 'code',
    createTime: 'createTime',
    username: 'username',
    phone: 'phone',
    enable: false,
  },
])

const items = ref([
  {
    prop: 'srk',
    is: 'currency-input',
    bind: {
      placeholder: '专业名称',
      clearable: true,
    },
  },
  {
    prop: 'epxlk',
    is: 'el-select-v2',
    bind: {
      options: [
        { label: '选项1', value: '1' },
        { label: '选项2', value: '2' },
      ],
      placeholder: '状态',
      clearable: true,
    },
  },

  {
    is: 'currency-button',
    bind: {
      color: '#6f6f6f',
      title: '清空',
      icon: 'DsrzClear',
    },
    on: { click: reset },
  },
])

const btns = ref([
  {
    is: 'currency-button',
    bind: {
      color: '#178782',
      title: '导入专业',
      icon: 'DsrzExport',
    },
    on: {
      click: () => {
        resetForm() // 重置表单
        dialogTitle.value = '导入专业'
        dialogType.value = 'import'
        Object.assign(form, { 
            details: { file: [], deptId: '' } as FormDetails // 重置表单，设置默认值
          })
        openDialog()
      },
    },
  },
  {
    is: 'currency-button',
    bind: {
      color: '#178782',
      title: '下载导入模版',
      icon: 'DsrzExport',
    },
    on: {
      click: () => {
       console.log('== 下载导入模版')
      },
    },
  },
  {
    is: 'currency-button',
    bind: {
      type: 'primary',
      title: '新增',
      icon: 'DsrzAdd',
    },
    on: {
      click: () => {
        resetForm() // 重置表单并设置默认值
        dialogTitle.value = '新增专业'
        dialogType.value = 'add'
        openDialog()
      },
    },
  },
])

const columns = ref([
  // { type: 'selection', width: '55px' },
  { label: '序号', type: 'index', width: '80px', align: 'center' },
  { label: '所属二级学院', prop: 'deptName', isDecrypt: true },
  { label: '专业名称', prop: 'name' },
  { label: '专业代码', prop: 'code' },
  { label: '创建时间', prop: 'createTime' },
  { label: '负责人', prop: 'username' },
  { label: '手机号', prop: 'phone' },
  { 
    label: '状态', 
    prop: 'enable', 
    is: 'currency-switch',
    on: {
      change: async (value: any) => {
        console.log('== 222 ', value)
        try {
          // const res = await specialitySwitch(value)
          ElMessage.success('操作成功')
        } catch (e) {
        }

      },
    } 
  },
  {
    label: '操作',
    is: 'currency-more',
    list: [
      {
        is: 'currency-button',
        bind: { type: 'primary', link: true, title: '修改' },
        on: {
          click: (e: any, d: any) => {
            dialogTitle.value = '修改专业'
            dialogType.value = 'add'
            console.log('== row ', d)
            Object.assign(form, { 
              details: { enable: 0, name: '测试专业名称', deptId: '2' } as FormDetails // 重置表单，设置默认值
            })
            openDialog()
          }
        }
      },
    ],
  },
])


const openDialog = () => {
  Object.assign(form, { visible: true })
}

const resetForm = () => {
  Object.assign(form, { 
    details: { enable: 1 } as FormDetails // 重置表单，设置默认值
  })
}
const dialogTitle = ref<string>('')
const dialogType = ref<'import' | 'add'>('add') // 对话框类型：import-导入，add-新增

const form = reactive({
  visible: false,
  size: 'default',
  details: {} as FormDetails,
  items: [
    {
      label: '所属二级学院',
      prop: 'deptId',
      is: 'currency-select',
      display: true, // 导入和新增都显示
      bind: {
        clearable: true,
        placeholder: '请选择所属二级学院',
        options: [
          { label: '选项1', value: '1' },
          { label: '选项2', value: '2' },
        ],
      },
    },
    {
      label: '专业名称',
      prop: 'name',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入专业名称',
      },
    },
    {
      label: '专业代码',
      prop: 'code',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入专业代码',
      },
    },
    {
      label: '负责人',
      prop: 'userId',
      is: 'currency-select',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        clearable: true,
        placeholder: '请选择负责人',
        options: [
          { label: '负责人1', value: 'fz-1' },
          { label: '负责人2', value: 'fz-2' },
        ],
      },
      on: {
        change: (value: string) => {
          console.log('===  负责人', value)
          // 根据负责人设置对应的手机号
          const phoneMap: Record<string, string> = {
            'fz-1': '12345678914',  // 负责人1的手机号
            'fz-2': '13888888888',  // 负责人2的手机号
          }
          form.details.phone = phoneMap[value] || ''
        }
      }
    },
    {
      label: '手机号',
      prop: 'phone',
      is: 'el-input',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请输入手机号',
        disabled: true,
      },
    },
    {
      label: '状态',
      prop: 'enable',
      is: 'currency-radio',
      display: (value: any, row: any) => dialogType.value === 'add', // 只有新增时显示
      bind: {
        placeholder: '请选择状态',
        options: [
          { label: '启用', value: 1 },
          { label: '禁用', value: 0 },
        ],
      },
    },
    {
      label: '选择文件',
      prop: 'file',
      is: 'currency-upload',
      display: (value: any, row: any) => dialogType.value === 'import', // 只有导入时显示
      bind: {
        limit: 1,
        accept: '.xlsx,.xls',
        buttonTitle: '选择文件',
        httpRequest:()=>{
          console.log('1111')
        }
      },
      // on: {
      //   change:(file: any, fileList: any) => {
      //     console.log('== e ', file)
      //     console.log('== fileList ', fileList)

      //     form.details.file = fileList;

      //     if (fileList.length) {
      //       refs.formRef.clearValidate(['file'])
      //     }
      //   }
      // }
    },

  ],
  rules: {
    deptId: [{ required: true, message: '请选择所属二级学院', trigger: 'blur' }],
    name: [{ required: true, message: '请输入专业名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入专业代码', trigger: 'blur' }],
    userId: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
    phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    enable: [{ required: true, message: '请选择状态', trigger: 'blur' }],
    file: [{ required: true, message: '请选择文件', trigger: 'blur' }],
  },
})

const handleConfirm = async () => {
  // 通过全局 refs 访问表单实例
  const formInstance = refs.formRef
  
  console.log('111', form.details)
  if (formInstance) {
    // 触发表单验证
    const isValid = await formInstance.validate()
    if (isValid) {
      // 验证通过，执行确认逻辑
      console.log('表单验证通过', form.details)
      form.visible = false
    } else {

      // 验证失败
      console.log('表单验证失败', form.details)
      return false // 阻止对话框关闭
    }
  } else {
    console.log('表单实例未找到')
    return false
  }
}

const request = (params:any) => list(params)

</script>
<template>
  <div>
    <CurrencyTable
      :data="data"
      :params="params"
      :request="request"
      :items="items"
      :btns="btns"
      :columns="columns"
    />
  </div>

  <div>
    <CurrencyDialog
      v-model="form.visible"
      :title="dialogTitle"
      :size="form.size"
      @cancel="form.visible = false"
      @confirm="handleConfirm"
      >
      <CurrencyForm
        ref="formRef"
        v-model="form.details"
        :items="form.items"
        :rules="form.rules"
        label-position="top"
      />
    </CurrencyDialog>
  </div>
  
</template>
